package com.gw.booking.service;

import com.gw.booking.common.ApiException;
import com.gw.booking.common.Constant;
import com.gw.booking.common.MessageCode;
import com.gw.booking.dto.backend.CityListDtoOut;
import com.gw.booking.entity.City;
import com.gw.booking.entity.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CityService {
    @Autowired
    private SessionFactory sessionFactory;

    public List<CityListDtoOut> list() {
        Session session = sessionFactory.getCurrentSession();
        String sql = "select id,name,name_c as nameC  from city where del_Flag = 0 order by sort_no asc";
        List<CityListDtoOut> cityListDtoOuts = session.createSQLQuery(sql)
                .setResultTransformer(Transformers.aliasToBean(CityListDtoOut.class)).list();
        return cityListDtoOuts;
    }

    public City get(Integer id) {
        Session session = sessionFactory.getCurrentSession();
        City city = (City) session.createCriteria(City.class)
                .add(Restrictions.eq("id", id))
                .add(Restrictions.eq("delFlag", Constant.FALSE))
                .uniqueResult();
        if (city == null) {
            throw new ApiException(MessageCode.CODE_CITY_ERROR);
        }
        return city;
    }

    public City getCityByName(String name) {
        Session session = sessionFactory.getCurrentSession();
        City city = (City) session.createCriteria(City.class)
                .add(Restrictions.eq("name", name))
                .add(Restrictions.eq("delFlag", Constant.FALSE))
                .uniqueResult();
        if (city == null) {
            throw new ApiException(MessageCode.CODE_CITY_ERROR);
        }
        return city;
    }

}
